package com.warski.wonderfires;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.location.LocationManager;
import android.net.wifi.WifiManager;
import android.os.Build;
import java.util.Locale;
import androidx.annotation.NonNull;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;

import com.warski.wonderfires.dlna.params.SettingsConstants;
import com.warski.wonderfires.net.TCPConn;
import com.warski.wonderfires.utils.LocaleUtils;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import static com.warski.wonderfires.dlna.params.SettingsConstants.PREF_SETTINGS_IP;

public class TheApplication extends Application {

    public static boolean isConnection = false;
    public static boolean isOpenApp = true;
    public static int gearsData = 0;
    private static TheApplication instance;

    private SharedPreferences mSettingsShared;
    public static String localGateIP = "";
    public static int localGatePort = 9090;
    public static int width;
    public static int height;
    public static Activity mActivity;
    public static Context mContext;

    public static TheApplication getInstance() {
        if (instance == null) {
            throw new NullPointerException("App instance hasn't registered");
        }
        return instance;
    }
    private MutableLiveData<String> mBroadcastData;

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action == null) {
                return;
            }
            switch (action) {
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:
                case LocationManager.PROVIDERS_CHANGED_ACTION:
                    mBroadcastData.setValue(action);
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        Locale _UserLocale= LocaleUtils.getUserLocale(this);
        LocaleUtils.updateLocale(this, _UserLocale);
        instance = this;
        mSettingsShared = getSharedPreferences(SettingsConstants.PREF_SETTINGS_NAME, Context.MODE_PRIVATE);
        localGateIP = (String) settingsGet(PREF_SETTINGS_IP,"");
        if (!localGateIP.isEmpty()) connect();

        mBroadcastData = new MutableLiveData<>();
        IntentFilter filter = new IntentFilter(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            filter.addAction(LocationManager.PROVIDERS_CHANGED_ACTION);
        }
        registerReceiver(mReceiver, filter);
    }

    public void observeBroadcast(LifecycleOwner owner, Observer<String> observer) {
        mBroadcastData.observe(owner, observer);
    }

    public void observeBroadcastForever(Observer<String> observer) {
        mBroadcastData.observeForever(observer);
    }

    public void removeBroadcastObserver(Observer<String> observer) {
        mBroadcastData.removeObserver(observer);
    }

    public void connect(){
        new Thread(() -> TCPConn.getInstance().tryNetAddr(localGateIP,localGatePort,3000)).start();
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
        unregisterReceiver(mReceiver);
    }

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Locale _UserLocale=LocaleUtils.getUserLocale(this);
        //系统语言改变了应用保持之前设置的语言
        if (_UserLocale != null) {
            Locale.setDefault(_UserLocale);
            Configuration _Configuration = new Configuration(newConfig);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                _Configuration.setLocale(_UserLocale);
            } else {
                _Configuration.locale =_UserLocale;
            }
            getResources().updateConfiguration(_Configuration, getResources().getDisplayMetrics());
        }
    }



    /**通过SharedPreferences存放蓝牙搜索功能过滤值*/
    public void settingsPut(String key, Object value) {
        SharedPreferences.Editor editor = mSettingsShared.edit();
        if (value instanceof String) {
            editor.putString(key, (String) value);
        } else if (value instanceof Boolean) {
            editor.putBoolean(key, (Boolean) value);
        } else if (value instanceof Float) {
            editor.putFloat(key, (Float) value);
        } else if (value instanceof Integer) {
            editor.putInt(key, (Integer) value);
        } else  if (value instanceof Long) {
            editor.putLong(key, (Long) value);
        } else if (value instanceof Set) {
            Set set = (Set) value;
            Set<String> newSet = new HashSet<>();
            for (Object object : set) {
                newSet.add((String)object);
            }
            editor.putStringSet(key, newSet);
        } else {
            throw new IllegalArgumentException("Unsupported value type");
        }

        editor.apply();
    }

    public Object settingsGet(String key, Object defaultValue) {
        if (defaultValue instanceof String) {
            return mSettingsShared.getString(key, (String) defaultValue);
        } else if (defaultValue instanceof Boolean) {
            return mSettingsShared.getBoolean(key, (Boolean) defaultValue);
        } else if (defaultValue instanceof Float) {
            return mSettingsShared.getFloat(key, (Float) defaultValue);
        } else if (defaultValue instanceof Integer) {
            return mSettingsShared.getInt(key, (Integer) defaultValue);
        } else if (defaultValue instanceof Long) {
            return mSettingsShared.getLong(key, (Long) defaultValue);
        } else if (defaultValue instanceof Set) {
            //noinspection unchecked
            return mSettingsShared.getStringSet(key, (Set<String>) defaultValue);
        } else {
            return null;
        }
    }
}
